﻿using System;
using System.Collections;
using System.Collections.Generic;
using HR60_PanelSoft.Model;
using HR60_PanelSoft.Model.BaseModel;
using HR60_PanelSoft.View.Base;

namespace HR60_PanelSoft.View.TabForms.ListItems
{
    //GC: [g1]修改面板编辑架构。[PinItem]@sx
    //GC: [g2]面板编辑保存[PinItem]@s1
    //GC: [g3]面板编辑加载[PinItem]@s1
    //GC: [g4]开合类负载[PinItem]@s4
    //GC: [g5]温控器类设备编辑[PinItem]@s6
    //GC: [g6]负载反向绑定到设备[PinItem]
    //GC: [g7]设备单次绑定限制[PinItem]
    //GC: [g8]485高级设备绑定，第一通道bug[PinItem]

    //GC: [g9]通过设备组，解绑设备，存在bug[PinItem]

    //GC: [g10]智能终端逻辑优化[PinItem]

    //GC: [g11]联调7-21-1：485类型高级设备逻辑[PinItem]
    //GC: [g12]联调7-21-3：温控器型空调4/5路选择问题[PinItem]
    //GC: [g13]联调7-23-1：开合类设备取消关联bug[PinItem]
    //GC: [g14]bug2182/2183/2184[PinItem]
    //GC: [g19]bug2192/2203/2204/2205[PinItem]
    //GC: [g20]优化：4bug2191[PinItem]
    //GC: [g21]bug2194[PinItem]
    //GC: [g22]bug2499[PinItem]
    //GC: [g23]bug2950[PinItem]
    //GC: [g24]bug2959[PinItem]
    //GC: [g25]bug3010[PinItem]
    //GC: [g26]bug3014/3015[PinItem]
    //GC: [g27]bug3016/3018[PinItem]
    //GC: [g28]bug2958[PinItem]

    /* [g12.s3] */
    //public delegate void AirControlEventHandler(AirControlEventArgs acea);
    //public class AirControlEventArgs : EventArgs
    //{
    //    public bool IsSeleceted = false;
    //    public AirControlEventArgs(bool isSelected)
    //    {
    //        IsSeleceted = isSelected;
    //    }
    //}
    /* end of [g12.s3] */

	public partial class PinItem : BaseFormControl
	{
        /* [g12.s1]增加事件 */

        //public AirControlEventHandler OnAirControlSelecetChanged;
        /* end of [g12.s1] */


		// 运行时长最大值
        /* [g14.s1] */
		//private static readonly int TIME_MAX = 30;
        private static readonly int TIME_MAX = 900;
        /* end of [g14.s1] */

        /* [g13.s1] */
        private Device _lastDevice = null;
        /* end of [g13.s1] */

		private Pin pin;

        /* [g27.s3]增加面板字段，增加销量 */
        private Panel _pnl = null;
        /* end of [g27.s3] */


		public Pin TagPin
		{
			get
			{
				return pin;
			}
		}

        /* [g4.s1]增加主副通道字段，用来辅助开合类负载 */
        /// <summary>
        /// true表示主通道，可以绑定开合类设备；false表示副通道，不可以绑定开合类设备。
        /// </summary>

        public bool IsMainChannel
        {
            get
            {
                /* index从0开始 */
                /* [g5.s5]使能分辨高级设备的主通道 */
                Device d0 = pin.getConnectedDevice();
                
                if (d0 == null)
                    return pin.index % 2 == 0;
                Device d = Device.findParent(d0);
                if(d == null)
                    return pin.index % 2 == 0;
                
                switch (d.type.exType)
                {
                    case ExDeviceType.NULL:
                        break;
                    case ExDeviceType.CentralAircon:
                        return pin.index == 0;
                    case ExDeviceType.CentralNewWind:
                        return pin.index == 0;
                    default:
                        break;
                }

                return pin.index % 2 == 0;  

                /* end of [g5.s5] */
            }
            set
            {

                this.Enabled = value;

            }
        }

        /* end of [g4.s1] */

        /* [g5.s6] */
        string[] ExDevSwitchTypes = new string[5] 
        {"高风","中风","低风","电磁阀1","电磁阀2" };

        /* end of [g5.s6] */


        /* [g5.s1] */
        public bool isFirstChannel
        {
            get
            {
                return pin.index == 0;
            }
            set
            {
                this.Enabled = value;
            }
        }
        /* end of [g5.s1] */



        /* [g4.s3] 获取负载通道名称  */

        public string ChannelName
        {
            get
            {
                return ltlName.Text;
            }
            set
            {
                ltlName.Text = value;
            }
        }

        /* end of [g4.s3] */

	    public PinItem(Pin pin, string name)
		{
			InitializeComponent();

            /* [g14.s2] */

            /* end of [g14.s2] */
            initByPin(pin, name);

            /* [g27.s4]获取当前面板 */
            _pnl = pin.getPanel();
            if (_pnl == null)
            {
                //GCERR:
                return;
            }
            /* end of [g27.s4] */
		}

        /* [g1.s1] 将初始化步骤封装方法 */
        /*
         * 封装成方法，方便开合类负载调用
         */
        private void initByPin(Pin pin, string name)
        {

            
            /* [g5.s4] 修改逻辑，不应该复制pin，而是只传递关联设备 */
            this.pin = pin;

            /* end of [g5.s4] */



            // 查找关联的设备及分组
            Device device = null;
            Device sub = null;

            /*[g4.s4] 增加空类型的判断 */
            findDeviceByUuid(pin.connectedDevice, ref device, ref sub);
            DeviceGroup group = findGroupByDeviceUuid(pin.connectedDevice);
            //DeviceGroup group = null;

            //if (null != pin)
            //{
            //    findDeviceByUuid(pin.connectedDevice, ref device, ref sub);
            //    findGroupByDeviceUuid(pin.connectedDevice);
            //}

            /* end of [g4.s4] */

            /* [g6.s1]反向绑定到设备 */
            //if (device == null)
            //{
            //    //GCERR:
            //    return;
            //}
            if (device != null && sub != null)
            {
                if (!sub.connectedPins.Exists(x => x == this.pin.uuid))
                    sub.connectedPins.Add(this.pin.uuid);

            }
            else if (device != null && sub == null)
            {
                if (!device.connectedPins.Exists(x => x == this.pin.uuid))
                    device.connectedPins.Add(this.pin.uuid);
            }


            /* end of [g6.s1] */

            /* [g5.s2] 先关闭事件捕获，否则会刷新至卡死。有待优化 */
            CatchValueChange = false;

            /* end of [g5.s2] */

            // 标题
            ltlName.Text = name;

            // 设备分组
            selGroup.setStaticFirstItem("选择设备分组");
            selGroup.bindData((IList)deviceGroups, "name");
            if (group != null) selGroup.Value = group;
            selGroup.ValueChanged += new ValueChangedHandler(selGroup_ValueChanged);
            
            /*[g7.s4] 为设备框绑定DropDownClose事件 */

            /* end of [g7.s4] */

            // 设备
            selDevice.setStaticFirstItem("选择设备");
            refreshDeviceList(group, device);
            selDevice.ValueChanged += new ValueChangedHandler(selDevice_ValueChanged);


            /*[g7.s4] 为设备框绑定DropDownClose事件 */
            selDevice.addDropDownClosedEvent(DropDownClosedEvent);

            /* end of [g7.s4] */

            /* [g13.s4]为设备框绑定DropDown事件 */
            selDevice.addDropDownEvent(DropDownEvent);
            /* end of [g13.s4] */

            // 分机

            /* [g11.s2]加载分机 */
            //bool is485ExType = false;
            //this.selSub.Enabled = true;
            if (pin.type == PinType.M485)
            {
                if (pin.connectedDevice != null)
                {
                    Device tempDev = pin.getConnectedDevice();
                    if (tempDev == null)
                    {
                        //GCERR:
                        return;
                    }
                    if (tempDev.type.name.Contains("分机")) /* 如果是485类高级设备 */
                    {
                        //is485ExType = true;
                        this.selSub.Enabled = false;
                    }
                }
            }
            //this.selSub.Enabled = !is485ExType;/* 设置selSub状态 */
            /* end of [g11.s2] */
            selSub.setStaticFirstItem("选择分机");
            refreshSubList(device, sub);
            //selSub.ValueChanged += new EventHandler(valueChange);
            /*g1.s1  */
            /* 
             * 
             */
            /* s1 */
            selSub.ValueChanged += new ValueChangedHandler(selSub_ValueChanged);
            /* end of s1 */

            /*[g7.s4] 绑定DropDownClose事件 */
            selSub.addDropDownClosedEvent(DropDownClosedEvent);
            /* end of [g7.s4] */

            /* [g21.s5]绑定DropDown事件 */
            selSub.addDropDownEvent(DropDownEvent);
            /* end of [g21.s5] */

            // 时长
            if (pin.type == PinType.L || pin.type == PinType.T)
            {
                //[g3.s1]
                Dictionary<string, int> timelist = new Dictionary<string, int>();
                for (int i = 0; i <= TIME_MAX; i++)
                {
                    timelist.Add(i.ToString(), i);
                }
                selTime.bindData(timelist);
                /* end of [g3.s1] */
                resetTimeSel();
                selTime.Value = ((LoadPin)pin).time;
                //selTime.Value = 3;

                //selTime.ValueChanged += new EventHandler(valueChange);
                /*[g1.s2] 更换selTime事件 */
                /* 
                 * 
                 */
                /* s1 */

                selTime.ValueChanged += new ValueChangedHandler(selTime_ValueChanged);
                /* end of g1.s2 */

                /* [g14.s4]增加TextChanged事件*/
                selTime.addTextChangedEvent(selTime_TextChanged);
                /* end of [g14.s4] */

            }

            /* [g4.s2] 同步状态；*/
            /* 
             * 在当前复制pin的逻辑下，无用 
             */
            //this.Enabled = pin.isMainPin;
            /* end of [g4.s2] */

            CatchValueChange = true;
        }
        /* end of [ g1.s1 ]*/


        /* [g5.s3]用于地暖的，只关联负载的connectedDev */
        /// <summary>
        /// 设置辅助负载通道，只传递连接设备
        /// </summary>
        /// <param name="pin"></param>
        /// <param name="name"></param>
        public void SetAssisPin(Pin pin,string name)
        {
            this.pin.connectedDevice = pin.connectedDevice;
            this.pin.isMainPin = false;

            // 查找关联的设备及分组

            Device d = null;
            Device p = null;
            p = Device.findParent(this.pin.connectedDevice, out d);
                
            
            // 标题
            ltlName.Text = name;
            selGroup.setStaticFirstItem("");
            if (p != null && d != null)
            {
                if (p.type.exType == ExDeviceType.CentralAircon || p.type.exType == ExDeviceType.CentralNewWind)
                    //selDevice.setStaticFirstItem(ExDevSwitchTypes[this.pin.index]);
                    selDevice.setStaticFirstItem("");
                if (!d.connectedPins.Exists(x => x == this.pin.uuid))
                    d.connectedPins.Add(this.pin.uuid);
            }
            else if (d != null && p == null)
            {
                if (d.type.switchTypes[0] == SwitchType.OPEN_JOIN)
                {
                    selDevice.setStaticFirstItem("开合");
                }
                if (!d.connectedPins.Exists(x => x == this.pin.uuid))
                    d.connectedPins.Add(this.pin.uuid);
            }
        }

        /* end of [g5.s3] */

        /* [g4.s3]增加重新关联Pin方法 */

        /// <summary>
        /// 重新设置关联的Pin
        /// 一般地，该方法只用在负载关联开合类设备的副通道时。
        /// </summary>
        /// <param name="pin">new pin</param>
        /// <param name="name">new name，displayed in TextBox </param>
        public void SetPin(Pin pin, string name)
        {
            initByPin(pin, name);
        }
        /* end of [g4.s3] */

        /* [g20.s1] */

        public void SetSub(Pin pin)
        {
            this.pin = pin;

            // 查找关联的设备及分组
            Device device = null;
            Device sub = null;

            /*[g4.s4] 增加空类型的判断 */
            findDeviceByUuid(pin.connectedDevice, ref device, ref sub);
            DeviceGroup group = findGroupByDeviceUuid(pin.connectedDevice);

            if (device != null && sub != null)
            {
                if (!sub.connectedPins.Exists(x => x == this.pin.uuid))
                    sub.connectedPins.Add(this.pin.uuid);

            }
            else if (device != null && sub == null)
            {
                if (!device.connectedPins.Exists(x => x == this.pin.uuid))
                    device.connectedPins.Add(this.pin.uuid);
            }
            /* [g20.s3] */
            else if (device == null)
            {
                
            }
            /* end of [g20.s3] */

        }

        /* end of [g20.s1] */

		// 刷新设备列表，同时联动运行时长
		private void refreshDeviceList(DeviceGroup group, Device selectedDevice)
		{
			// 刷新设备列表
			IList<Device> list = new List<Device>();
			if (group != null)
			{
				foreach (Device dev in group.devices)
				{
					if (
						(pin.type == dev.type.pinType) ||
						(pin.type == PinType.T && dev.type.pinType == PinType.LT) ||
						(pin.type == PinType.L && dev.type.pinType == PinType.LT) ||
						(
							dev.type.subDeviceType != null &&
							(
								(pin.type == dev.type.subDeviceType.pinType) ||
								(pin.type == PinType.T && dev.type.subDeviceType.pinType == PinType.LT) ||
								(pin.type == PinType.L && dev.type.subDeviceType.pinType == PinType.LT))
							)
						)
					{
						list.Add(dev);
					}
				}
			}
			selDevice.bindData((IList)list, "nickName");   //GC:说明设备的nickname是唯一的
			selDevice.Value = selectedDevice;

        }

		// 刷新分机列表
		private void refreshSubList(Device device, Device selectedSub)
		{
			// 刷新设备列表
			if (device == null || device.type.subDeviceType == null)
			{
				selSub.Visible = false;
				return;
			}
			selSub.Visible = true;
			selSub.bindData((IList)device.childDevices, "nickName");

			// 选中目标设备
			if (selectedSub != null)
			{
				selSub.Value = selectedSub;
			}
		}

		// 分组选择事件
        void selGroup_ValueChanged(object sender, ValueChangedEventArgs e)
		{
            /* [g10.s2] 将[g9][PinItem][s1]转移到DropDownClosedEvent中*/
            /* [g9.s1] */


            /* 清理设备的pin关联 */
            //if (pin.connectedDevice != null)
            //{
            //    Device d = pin.getConnectedDevice();
            //    d.connectedPins.Remove(pin.uuid);

            //    /* 清理pin的设备关联 */
            //    pin.connectedDevice = null;
            //}

            //selDevice.Value = null;
            //selSub.Value = null;
            /* end of [g9.s1] */

            /* end of [g10.s2] */

			selDevice.CatchValueChange = false;
			selSub.CatchValueChange = false;
			selTime.CatchValueChange = false;

			refreshDeviceList((DeviceGroup)selGroup.Value, null);
			refreshSubList((Device)selDevice.Value, null);
			resetTimeSel();

			selDevice.CatchValueChange = true;
			selSub.CatchValueChange = true;
			selTime.CatchValueChange = true;

            e.Type = EventType.GroupInPinItem;
			valueChange(this, e);
		}

		// 设备选择事件
        void selDevice_ValueChanged(object sender, ValueChangedEventArgs e)
		{
            
            /* 
             * [g2.s3] 在设备控件改变时，保存到对象
             * 注意：这里是否需要考虑开合设备？——yes
             */
            /* 当设备已经选择下拉选项，则保存到内存对象  */
            if (null != this.selDevice.Value)
            {
                /* [g7.s1]判断无分机的设备是否已关联 */
                Device p = (Device)this.selDevice.Value;
                //if (p.childDevices.Count < 1) /* 无分机设备 */
                //{
                //    if (p.type.pinLen != 0 && p.connectedPins.Count == p.type.pinLen)
                //    {
                //        ViewUtils.showAlert(" 该设备已被关联，请选择其他设备！ ");
                //        return;
                //    }
                //}

                /* end of [g7.s1] */
                ///* [g4.s2] 当为副通道时，判断是否开合类设备 */
                //if (p.type.switchTypes.Count > 0)
                //    if (p.type.switchTypes[0] == SwitchType.OPEN_JOIN
                //        && !IsMainChannel)
                //    {
                //        this.selDevice.Value = null;
                //        ViewUtils.showAlert(" 副通道不能绑定开合类设备！ ");
                //    }
                //    /* end of [g4.s2] */
                if (p.type.subDeviceMax < 1)
                    this.pin.connectedDevice = p.uuid;
                /* [g24.s2]联调7-21-1导致的衍生bug：485高级设备不能保存 */
                else if (p.type.exType == ExDeviceType.CentralAircon ||
                    p.type.exType == ExDeviceType.CentralHeating ||
                    p.type.exType == ExDeviceType.CentralNewWind ||
                    p.type.exType == ExDeviceType.BGM)
                {
                    //NOP;
                }
                /* [g24.s1]bug2959的衍生bug:当高级设备只选择selDevice也会填充connectedPin */
                else
                    this.pin.connectedDevice = null;
                /* end of [g24.s1] */
            }
            /*[g4.s4] 消除选择复位值的干扰*/
            else 
            {
                this.pin.connectedDevice = null;
            }
            /*end of [g4.s4*/
            /* end of [g2.s3] */

            selSub.CatchValueChange = false;
            selTime.CatchValueChange = false;

			refreshSubList((Device)selDevice.Value, null);
			resetTimeSel();

			selSub.CatchValueChange = true;
			selTime.CatchValueChange = true;

            e.Type = EventType.DeviceInPinItem;
			valueChange(this, e);
		}

        //GC: 增加子设备值更改操作s1
        /*
         * 
         */
        /* s1 */
        void selSub_ValueChanged(object sender, ValueChangedEventArgs e)
        {
            if (null != selSub.Value)
            {
                /* [g5.s7]温控器设备的通道选择限制 */

                /* [g7.s2]判断无分机的设备是否已关联 */
                //Device d = (Device)this.selSub.Value;
                ////if (d.type.pinLen != 0 && d.connectedPins.Count == d.type.pinLen)
                ////{
                ////    ViewUtils.showAlert(" 该分机已被关联，请选择其他设备！ ");
                ////    return;
                ////}

                /* end of [g7.s2] */

                Device p = null;
                Device d = (Device)this.selSub.Value;
                p = Device.findParent(d);

                if (p.type.group == "温控器类")
                {
                    /* 空调 */
                    //if ((p.type.exType == ExDeviceType.CentralAircon || p.type.exType == ExDeviceType.CentralNewWind )&&
                    //    !this.isFirstChannel) 
                    //{

                    //    ViewUtils.showAlert(d.nickName + "必须挂在第一个负载上！");
                    //    this.pin.connectedDevice = null;
                    //    this.SetPin(this.pin, this.ChannelName);
                    //    return;
                    //}
                }

                /* end of [g5.s7] */

                if (d.type.subDeviceMax < 1 )
                    this.pin.connectedDevice = d.uuid;
            }
            selTime.CatchValueChange = false;
            resetTimeSel();
            selTime.CatchValueChange = true;

            e.Type = EventType.SubInPinItem ;
            valueChange(this, e);
        }
        /*end of s1*/

       

        /* [g2.s1]运行时间值改变事件 */

        void selTime_ValueChanged(object sender, ValueChangedEventArgs e)
        {
            //if (null != selTime.Value && selTime.Visible)
            //{
            //    ((LoadPin)pin).time = (int)selTime.Value;
            //}
            int tempN = 0;
            if (selTime.Text == string.Empty)
                return;
            if (!int.TryParse(selTime.Text, out tempN))
            {
                View.ViewUtils.showAlert("请输入整数值");
                return;
            }
            ((LoadPin)pin).time = tempN;

            e.Type = EventType.TimeInPinItem;
            valueChange(this, e);
        }

        /*end of s1*/
        /* [g14.s3] */
        private void selTime_TextChanged(object sender, EventArgs e)
        {
            int tempN = 0;
            if (!int.TryParse(selTime.Text, out tempN))
            {
                selTime.Text = "0";
                return;
            }
            ValueChangedEventArgs vcea = new ValueChangedEventArgs(EventType.TimeInPinItem);
            valueChange(sender, vcea); 
        }
        /* end of [g14.s3] */

        /* [g7.s3]DropDownEvent&DropDownClosedEvent */
        /* [g13.s2] */
        void DropDownEvent(object sender, EventArgs e)
        {
            System.Windows.Forms.ComboBox cb = (System.Windows.Forms.ComboBox)sender;
            BaseFormControl bfc = (BaseFormControl)cb.Parent;
            if (bfc == null)
                return;
            if (bfc.Name == selDevice.Name)
            {
                _lastDevice = (Device)selDevice.Value;
            }
            /* [g21.s2] */
            else if (bfc.Name == selSub.Name)
            {
                _lastDevice = (Device)selSub.Value;
            }
            /* end of [g21.s2] */
        }

        /* end of [g13.s2] */
        void DropDownClosedEvent(object sender, EventArgs e)
        {
            System.Windows.Forms.ComboBox cb = (System.Windows.Forms.ComboBox)sender;
            BaseFormControl bfc = (BaseFormControl)cb.Parent;
            if (bfc == null)
                return;

            /* [g10.s3] 将[g9][PinItem][s1]转移到DropDownClosedEvent中 */
            if (bfc.Name == selGroup.Name)
            {
                if (pin.connectedDevice != null)
                {
                    Device d = pin.getConnectedDevice();
                    d.connectedPins.Remove(pin.uuid);

                    /* 清理pin的设备关联 */
                    pin.connectedDevice = null;
                }

                selDevice.Value = null;
                selSub.Value = null;
            }

            /* end of [g10.s3] */
            if (bfc.Name == selDevice.Name || bfc.Name == selSub.Name)
            {
                Device d = (Device)bfc.Value;

                /* [g12.s2] 处理4/5路负载问题 */

                //if (bfc.Name == selDevice.Name && this.isFirstChannel)
                //{
                //    if (d != null && d.type.name == "中央空调系统-温控器型")
                //    {
                //        OnAirControlSelecetChanged(new AirControlEventArgs(true));
                //    }
                //    else
                //    {
                //        OnAirControlSelecetChanged(new AirControlEventArgs(false));
                //    }
                //}

                /* end of [g12.s2] */

                /* [g21.s3]关联新设备后，解绑之前设备 */
                ///* [g13.s3] */
                //if (d == null)
                //{
                //    if (_lastDevice != null)
                //    {
                //        if (!_lastDevice.connectedPins.Remove(this.pin.uuid))
                //        {
                //            //GCERR:
                //            return;
                //        }
                //    }

                //    /* [g13.s5]更新_lastDevice  */
                //    _lastDevice = d;
                //    /* end of [g13.s5] */
                //    return;
                //}

                ///* end of [g13.s3] */
                ///

                if (_lastDevice != null)
                {
                    /* [g22.s1] 对于485设备，需要清除第一个分机的关联 */
                    if (_lastDevice.childDevices.Count > 0)
                    {
                        if (!_lastDevice.childDevices[0].connectedPins.Remove(this.pin.uuid))
                        {
                            //GCERR:
                            return;
                        }
                    }
                    else 
                    /* end of [g22.s1] */
                    if (!_lastDevice.connectedPins.Remove(this.pin.uuid))
                    {
                        //GCERR:
                        return;
                    }
                }
                
                /* end of [g21.s3] */

                if ( d != null && d.connectedPins.Count != 0 && d.connectedPins.Count == d.type.pinLen)
                {
                    foreach (string s in d.connectedPins)
                    {
                        if (this.pin.uuid == s)
                            return;
                    }
                    bfc.Value = null;
                    /* [g28.s2] */
                    this.pin.connectedDevice = null;
                    /* end of [g28.s2] */
                    ViewUtils.showAlert("该设备已被其他负载绑定，请重新选择！");
                    return;
                }

                /* [g5.s8] */
                if (d != null && bfc.Name == selSub.Name)
                {
                    /* [g19.s1] */
                    //Device p = Device.findParent(d);
                    //if (p == null)
                    //    return;

                    /* [g8.s1] */
                    //if ((p.type.exType == ExDeviceType.CentralAircon || p.type.exType == ExDeviceType.CentralNewWind) &&
                    //     !this.isFirstChannel )
                    //if ((p.type.exType == ExDeviceType.CentralAircon || p.type.exType == ExDeviceType.CentralNewWind) &&
                    //        !this.isFirstChannel  && p.type.group == "温控器类")
                    /* end of [g8.s1] */
                    /* [g20.s2] bug2950 */
                    //if (!this.isFirstChannel && d.type.name == "中央空调系统分机-温控器型"
                    //    || d.type.name == "新风系统分机-温控器型")
                    if (!this.isFirstChannel && (d.type.name == "中央空调系统分机-温控器型"
                        || d.type.name == "新风系统分机-温控器型"))
                    /* end of [g20.s2] */
                    /* end of [g19.s1] */
                    {
                        this.pin.connectedDevice = null;
                        this.SetPin(this.pin, this.ChannelName);
                        /* [g5.s9]消除selSub_ValueChanged影响 */
                        this.selSub.Value = null;
                        /* end of [g5.s9] */
                        ViewUtils.showAlert(d.nickName + "必须挂在第一个负载上！");
                        return;
                    }

                    /* [g21.s1] */

                    if (d.type.name == "中央供暖系统分机-温控器型")
                    {
                        /* 检查是否绑定至多个负载 */

                        foreach (LoadPin lp in _pnl.loadPins)
                        {
                            if (lp.connectedDevice != null)
                            {
                                Device tempD = lp.getConnectedDevice();
                                if (tempD.type.name == "中央供暖系统分机-温控器型" &&
                                    this.pin.index != _pnl.loadPins.IndexOf(lp))
                                {
                                    this.pin.connectedDevice = null;
                                    this.pin.isMainPin = true;
                                    this.SetPin(this.pin, this.ChannelName);
                                    this.selSub.Value = null;
                                    this.Enabled = true;

                                    d.connectedPins.Clear();

                                    View.ViewUtils.showAlert("一个面板中只能挂载一个温控器型中央供暖系统分机！\r\n");
                                    return;
                                }
                            }
                        }

                        
                    }

                    /* end of [g21.s1] */
                }
                /* end of [g5.s8] */

                /* [g4.s5] 优化开合类设备不能绑定副通道*/
                if (d != null && bfc.Name == selDevice.Name)
                { 
             

                    /* [g11.s3]先使能selSub */
                    this.selSub.Enabled = true;
                    /* end of [g11.s3] */
                    /* [g7.s1]判断无分机的设备是否已关联 */
                    //Device p = (Device)this.selDevice.Value;

                    //if (p == null)
                    //    return;
                    /* [g4.s2] 当为副通道时，判断是否开合类设备 */
                    if (d.type.switchTypes.Count > 0)
                        if (d.type.switchTypes[0] == SwitchType.OPEN_JOIN
                            && !IsMainChannel)
                        {
                            this.pin.connectedDevice = null;
                            this.selDevice.Value = null;
                            ViewUtils.showAlert(" 副通道不能绑定开合类设备！ ");
                            return;
                        }
                        /*[g26.s1]在此判断绑定开合类设备时的通道数问题*/
                        else
                        {
                            Panel tempPnl = this.pin.getPanel();
                            if (this.pin.index == tempPnl.loadPins.Count - 1)
                            {
                                this.selDevice.Value = null;
                                View.ViewUtils.showAlert("开合类设备需占用两个负载通道，绑定失败！");
                                return;
                            }
                        }
                        /* end of [g26.s1] */
                        /* end of [g4.s2] */



                    /* [g10.s1] 处理智能终端业务约束*/
                    if (this.pin.type == PinType.M485)
                    {
                        /* [g27.s5] */
                        /* 50Q6面板只能挂载多楼层主机和从机 */
                        if (_pnl.type.name == "HK-50Q6CW")
                        {
                            if ((d.type.name != "多楼层主机") && (d.type.name != "多楼层从机"))
                            {
                                this.selDevice.Value = null;
                                View.ViewUtils.showAlert("50Q6面板只能挂载多楼主机和多楼层从机！");
                                return;
                            }
                        }

                        /* end of [g27.s5] */
                        switch (d.type.name)
                        {
                            case "智能终端（灯光窗帘）":
                                /* 检测Q6面板 */
                                bool tempHasQ6 = true;
                                foreach (Net n in proj.nets)
                                {
                                    tempHasQ6 = false;
                                    foreach (HR60_PanelSoft.Model.Panel pnl in n.panels)
                                    {
                                        if (pnl.type.name == "HK-60Q6CW" || pnl.type.name == "HK-50Q6CW")
                                        {
                                            tempHasQ6 = true;
                                            break;
                                        }
                                    }
                                    if (!tempHasQ6)
                                    {
                                        this.pin.connectedDevice = null;
                                        this.selDevice.Value = null;
                                        View.ViewUtils.showAlert("在绑定智能终端（灯光窗帘）设备之前，" +
                                            "必须确保每个子网包含一个Q6面板！创建设备失败！");
                                        return;
                                    }
                                }

                                /* 检测智能终端（全部功能） */
                                //bool tempHasTypeZNZDAll = false;
                                //foreach (Net n in proj.nets)
                                //{
                                //    foreach (Panel pnl in n.panels)
                                //    {
                                //        if (pnl.type.name == "HK-60Q6CW" || pnl.type.name == "HK-50Q6CW")
                                //        {
                                //            if (pnl.m485Pin.connectedDevice == null)
                                //                continue;
                                //            if (pnl.m485Pin.getConnectedDevice().type.name == "智能终端（全部功能）")
                                //            {
                                //                tempHasTypeZNZDAll = true;
                                //                break;
                                //            }
                                //        }
                                //    }
                                //    if (tempHasTypeZNZDAll)
                                //        break;
                                //}
                                //if (!tempHasTypeZNZDAll)
                                //    return ;
                                //else
                                //{
                                //    View.ViewUtils.showAlert("当前项目中，已经关联了智能终端（全部功能）设备，" +
                                //        "不能再创建智能终端（灯光窗帘）设备！");
                                //    return;
                                //}
                                break;
                            case "智能终端（全部功能）":
                                /* 检测Q6面板 */
                                bool tempHasQ61 = true;
                                foreach (Net n in proj.nets)
                                {
                                    tempHasQ61 = false;
                                    foreach (HR60_PanelSoft.Model.Panel pnl in n.panels)
                                    {
                                        if (pnl.type.name == "HK-60Q6CW" || pnl.type.name == "HK-50Q6CW")
                                        {
                                            tempHasQ61 = true;
                                            break;
                                        }
                                    }
                                    if (!tempHasQ61)
                                    {
                                        this.pin.connectedDevice = null;
                                        this.selDevice.Value = null;
                                        View.ViewUtils.showAlert("在绑定智能终端（全部功能）设备之前，" +
                                            "必须确保每个子网包含一个Q6面板！创建设备失败！");
                                        return;
                                    }
                                }

                                /* 检测智能终端（全部功能） */
                                bool tempHasTypeZNZDAll = false;
                                foreach (Net n in proj.nets)
                                {
                                    foreach (Panel pnl in n.panels)
                                    {
                                        if (pnl.type.name == "HK-60Q6CW" || pnl.type.name == "HK-50Q6CW")
                                        {
                                            if (pnl.m485Pin.connectedDevice == null)
                                                continue;
                                            if (pnl.m485Pin.getConnectedDevice().type.name == "智能终端（全部功能）")
                                            {
                                                tempHasTypeZNZDAll = true;
                                                break;
                                            }
                                        }
                                    }
                                    if (tempHasTypeZNZDAll)
                                    {
                                        this.pin.connectedDevice = null;
                                        this.selDevice.Value = null;
                                        View.ViewUtils.showAlert("当前项目中，已经关联了智能终端（全部功能）设备，" +
                                            "不能再关联智能终端（全部功能）设备！");
                                        return;
                                    }

                                }
                                break;
                            /* [g11.s1]高级设备的绑定，默认绑定到第一个分机
                             * 只绑定到第一分机的connectedPins 
                             */
                            case "中央空调系统-485型":
                            case "中央供暖系统-485型":
                            case "新风系统-485型":
                            case "背景音乐系统":

                                /* 1.先判断其他面板有无绑定同类设备 */
                                Device tempParent = (Device)this.selDevice.Value;
                                if (tempParent == null)
                                {
                                    this.pin.connectedDevice = null;
                                    this.selDevice.Value = null;
                                    View.ViewUtils.showAlert("选择485设备为空，请重新选择！" );
                                    return;
                                }

                                if (tempParent.childDevices[0].connectedPins.Count > 0)
                                {
                                    if (tempParent.childDevices[0].connectedPins.Count != 1)
                                    {
                                        //GCERR:
                                        return;
                                    }
                                    if (tempParent.childDevices[0].connectedPins[0] == this.pin.uuid)
                                        return;
                                    this.pin.connectedDevice = null;
                                    this.selDevice.Value = null;
                                    View.ViewUtils.showAlert("该设备已被绑定!\r\n" +
                                        "请先解除绑定！");
                                    return;
                                }
                                //foreach (DeviceGroup dg in proj.deviceGroups)
                                //{
                                //    foreach (Device par in dg.devices)
                                //    {
                                //        if (par.type.exType == ExDeviceType.NULL)
                                //            continue;
                                //        if (par.uuid == tempParent.uuid)
                                //            continue;
                                //        if (par.type.exType == tempParent.type.exType )
                                //        {
                                //            /* connectedPins绑定到，子设备，但是缺少对子设备的遍历 */

                                //            if (par.childDevices[0].connectedPins.Count < 1)
                                //                break;

                                //                bool isExist = false;

                                //                foreach (string s in par.childDevices[0].connectedPins)
                                //                {
                                //                    if (tempParent.childDevices[0].connectedPins.Exists(x => x == s))
                                //                    {
                                //                        isExist = true;
                                //                        break;
                                //                    }
                                //                }

                                //                if (isExist)
                                //                {
                                //                    this.pin.connectedDevice = null;
                                //                    this.selDevice.Value = null;
                                //                    View.ViewUtils.showAlert("该设备已被绑定!\r\n" +
                                //                        "请先解除绑定！");
                                //                    return;
                                //                }

                                //        }


                                //    }
                                //}
                                
                                /* 2.subDevice选择第一个分机 */
                                /* [g11.s4] */
                                //selSub.setStaticFirstItem("选择分机");
                                //refreshSubList(tempParent, tempParent.childDevices[0]);


                                //List<System.Windows.Forms.Control> tempCtrls = selSub.GetCoreControls();
                                //foreach (System.Windows.Forms.Control c in tempCtrls)
                                //{
                                //    if (c is System.Windows.Forms.ComboBox)
                                //    {
                                //        ((System.Windows.Forms.ComboBox)c).SelectedIndex = 1; 
                                //        break;
                                //    }
                                //}

                                this.pin.connectedDevice = tempParent.childDevices[0].uuid;
                                tempParent.childDevices[0].connectedPins.Add(this.pin.uuid);


                                /* end of [g11.s4] */
                                /* 3.禁用subDevice */
                                this.selSub.Enabled = false;

                                return;
                            /* end of [g11.s1] */
                                /* [g25.s1] */
                            case "多楼层主机":
                                /* [g27.s1]先检测Panel类型，是否支持多楼层主机 */
                                if (true)
                                {
                                    switch (_pnl.type.name)
                                    {
                                        case "中央控制模块":
                                            this.pin.connectedDevice = null;
                                            this.selDevice.Value = null;
                                            View.ViewUtils.showAlert("中央控制模块，不能挂载多楼层主机！");
                                            return;
                                        default:
                                            break;
                                    }
                                }
                                /* end of [g27.s1] */
                                /* 检测当前项目是否存在多楼层主机 */
                                bool tempHasMaster = false;
                                foreach (Net n in proj.nets)
                                {
                                    foreach (Panel p in n.panels)
                                    {
                                        if ((p.uuid != _pnl.uuid) && p.type.hasM485Model)
                                        {
                                            if (p.m485Pin.connectedDevice != null)
                                            {
                                                Device temp485Dev = findDeviceByUuid(p.m485Pin.connectedDevice);
                                                if (temp485Dev == null)
                                                {
                                                    //GCERR:
                                                    return;
                                                }
                                                if (temp485Dev.type.name == "多楼层主机")
                                                {
                                                    tempHasMaster = true;
                                                }
                                            }
                                        }
                                    }
                                }
                                if (tempHasMaster)/* 如果找到主机，则报警 */
                                {
                                    this.selDevice.Value = null;
                                    View.ViewUtils.showAlert("一个项目中只能绑定一个多楼层主机负载，当前绑定数为【1】！");
                                    return;
                                }
                                break;
                            case "多楼层从机":
                                /* [g27.s2]先检测Panel类型，是否支持多楼层从机 */
                                if (true)
                                {
                                    switch (_pnl.type.name)
                                    {
                                        case "中央控制模块":
                                            this.pin.connectedDevice = null;
                                            this.selDevice.Value = null;
                                            View.ViewUtils.showAlert("中央控制模块，不能挂载多楼层从机！");
                                            return;
                                        default:
                                            break;
                                    }
                                }
                                /* end of [g27.s2] */
                                bool tempHasMaster1 = false;
                                foreach (Net n in proj.nets)
                                {
                                    foreach (Panel p in n.panels)
                                    {
                                        if ((p.uuid != _pnl.uuid) && p.type.hasM485Model)
                                        {
                                            if (p.m485Pin.connectedDevice != null)
                                            {
                                                Device temp485Dev = findDeviceByUuid(p.m485Pin.connectedDevice);
                                                if (temp485Dev == null)
                                                {
                                                    //GCERR:
                                                    return;
                                                }
                                                if (temp485Dev.type.name == "多楼层主机")
                                                {
                                                    tempHasMaster1 = true;
                                                }
                                            }
                                        }
                                    }
                                }
                                if (!tempHasMaster1)/* 如果未找到多楼层主机，警告 */
                                {
                                    this.selDevice.Value = null;
                                    View.ViewUtils.showAlert("一个项目中必须先绑定多楼层主机，当前多楼层主机绑定数为【0】！");
                                    return;
                                }
                                break;
                                /* end of [g25.s1] */
                            default:
                                break;
                        }
                    }

                    /* end of [g10.s1] */

                    this.pin.connectedDevice = d.uuid; 
                }
                /* end of [g4.s5] */
            }

        }


        /* end of [g7.s3] */

        /*  */

		private void resetTimeSel()
		{
			if (selDevice.Value != null)
			{
				// 开合类显示运行时间
				if (((Device)selDevice.Value).type.switchTypes.Contains(SwitchType.OPEN_JOIN))
				{
					selTime.Visible = true;
					selTime.Value = ((LoadPin)pin).time;
					ltlTime.Visible = true;
				}
				else
				{
					selTime.Visible = false;
					ltlTime.Visible = false;
				}
			}
			else
			{
				selTime.Visible = false;
				ltlTime.Visible = false;
			}
		}



		// 重写Value属性
		public override object Value
		{
			get
			{
                /* [g5.s4]增加 */
                IDictionary<string, object> res = new Dictionary<string, object>();

                if (!IsMainChannel)
                {
                    res.Add("device", pin.getConnectedDevice());
                    res.Add("time", 0);
                }
                else
                {
                    /* [g28.s1]应该区分SelDevice或SelSub */
                    //res.Add("device", selDevice.Value);
                    res.Add("device", selSub.Visible ? selSub.Value : selDevice.Value);
                    /* end of [g28.s1] */

                    res.Add("time", selTime.Value);
                }


                //IDictionary<string, object> res = new Dictionary<string, object>();
                //res.Add("device", selDevice.Value);
                //res.Add("time", selTime.Value);
				return res;

                /* end of [g5.s4] */
			}
			set
			{
				throw new Exception("read only");
			}
		}




        

	}
}
